var auth = require('auth.js');
const glocalConfig = {
  ajax:{
      rootHttp:'https://astronomy.spitech.com.cn'
  }
};
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function autoLogin(callBack){  
    auth.login().then(function(res) {        
        callBack(res)
    }, function(res) {
        callBack(res)
    })
}

function errorTip(){
    wx.showToast({
        title: '接口返回错误',
        icon: 'success',
        duration: 20000
    })
}
// 定义hy级别常用函数
  const ajax =  function(data){
      
      if(data && typeof data.config == 'undefined'){
        data.config = glocalConfig.ajax;
      }

      autoLogin(function(loginInfo){
          let url = data.config.rootHttp + data.url;
          let parameters = data.data;
          parameters = Object.assign(parameters, loginInfo);
          let successCallFun = data.success;
          let failCallFun = data.fail; //接口调用结束的回调函数（调用成功、失败都会执行）
          let method = data.method;  //	默认为 GET，有效值：OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          let complete = data.complete; //接口调用结束的回调函数（调用成功、失败都会执行）

          wx.request({
              url: url, //仅为示例，并非真实的接口地址
              data: parameters,
              method: method,
              header: {
                  'content-type': 'application/json'
              },
              success: function(res) {

                  if(typeof res == 'string'){
                      errorTip();
                      return false;
                  }
             
                  successCallFun && successCallFun(res.data);
              },
              fail: function(res){


                  failCallFun && failCallFun(res);
              },
              complete: function(res){
                 
                  if(res && res.data &&res.data.data && res.data.data._application && res.data.data._application.user && res.data.data._application.user.session_key){
                      wx.setStorageSync('sessionId', res.data.data._application.user.session_key);
                       
                  }
//               if(res.data.ret == 1 && res.data.msg == "Login Required"){ 
//                  wx.removeStorageSync('sessionId')
//               }
                  if(typeof res.data == 'string'){
                      errorTip();
                      return false;
                  }
                  complete && complete(res);

              }
          })
      });


  }
module.exports = { formatTime , ajax } 



